package com.heima.admin.v1.controller;

import com.heima.admin.pojo.AdChannel;
import com.heima.admin.service.AdChannelService;
import com.heima.common.dtos.PageResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.model.admin.dtos.ChannelDTO;
import com.heima.model.admin.dtos.ChannelQueryDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Fuqiang
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/channel")
public class ChannelController {

    @Autowired
    AdChannelService channelService;

    /**
     * 分页查询频道列表信息
     *
     * @param dto 查询条件
     * @return 频道列表信息
     */
    @PostMapping("/list")
    public PageResult<AdChannel> list(@RequestBody ChannelQueryDTO dto
            , @RequestHeader(name = "userId", defaultValue = "-1") Integer userId) {
        log.info("userId = {}", userId);
        return channelService.getListByCondition(dto);
    }


    /**
     * 根据条件保存频道列表
     *
     * @param dto
     * @return
     */
    @PostMapping("/save")
    public ResponseResult save(@RequestBody ChannelDTO dto) {
        return channelService.saveByDTO(dto);
    }


    /**
     * 修改频道信息
     *
     * @param dto
     * @return
     */
    @PutMapping("/update")
    public ResponseResult update(@RequestBody ChannelDTO dto) {
        return channelService.updateByDTO(dto);
    }

    /**
     * 根据频道id删除频道信息
     *
     * @param id 频道id
     * @return
     */
    @DeleteMapping("/del/{id}")
    public ResponseResult deleteById(@PathVariable("id") Long id) {

        // 根据频道id删除频道列表信息
        boolean flag = channelService.removeById(id);
        if (flag) {
            return ResponseResult.ok();
        }
        log.error("频道id删除失败, 频道id为:{}", id);
        throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
    }

    /**
     * 查询所有频道信息
     *
     * @return
     */
    @GetMapping("/channels")
    public ResponseResult<List<AdChannel>> getAll() {
        return ResponseResult.ok(channelService.list());
    }


    /**
     * 根据频道id查询频道名
     *
     * @param id
     * @return
     */
    @GetMapping("/getChannelName/{id}")
    public String getChannelNameById(@PathVariable("id") Integer id) {
        return channelService.getById(id).getName();
    }
}
